#include "chat.h"
#include "ui_chat.h"

#include <QtXml/QDomElement>
#include <QtXml/QDomDocument>
#include <QFile>

#include <QMessageBox>
#include <QTime>

Chat::Chat(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Chat)
{
    ui->setupUi(this);

    m_pClientConnection = new QTcpSocket();


    //============get the listen socket ip and port from confi.xml file==
    QFile file("Configure\\confi.xml");
    file.open(QIODevice::ReadOnly | QIODevice::Text);

    QString str = file.readAll();
    QDomDocument doc;
    doc.setContent(str,false);
    QDomNodeList list = doc.elementsByTagName("localhost");

    m_IP = list.at(0).firstChildElement("ip").text();
    m_Port = list.at(0).firstChildElement("port").text().toInt();
    //===================================================================

    if (startListen(m_IP,m_Port))
    {
        ui->m_lbTitle->setText("<font color=blue>chat function start sucessfully</font>");
        connect(&m_ListenSocket,SIGNAL(newConnection()),this,SLOT(processNewConnection()));
    }
    else
    {
        ui->m_lbTitle->setText("<font color=red>chat function can not start,please check your address</font>");
    }

    ///connect to your friend
    //processConnectionChange();
}

Chat::~Chat()
{
    delete ui;
}

void Chat::on_m_pbClean_clicked()
{

}

void Chat::on_m_pbSend_clicked()
{
    if (!m_bIsConnected)
    {
        QMessageBox::warning(this,"Error","you have not connect with your friend");
        return ;
    }
    //=========test==========================
    MSGHeader header;
    QByteArray data;
    data.append(ui->m_teSend->toPlainText());
    header.len = data.length();

    QByteArray package = generatePackage(header,data);
    m_pClientConnection->write(package);
    m_pClientConnection->flush();
    //=======================================

    ///deal new chat data recive from client
    QString str = ui->m_teRecv->toPlainText();

    QTime time = QTime::currentTime();
    QString time_str = time.toString("hh:mm:ss");

    QString lable = QString(tr("me")) + QString(tr(" ")) + time_str;
    QString record ;
    if (!str.isEmpty())
        record= str + QString(tr("\n")) + lable;
    else
        record = lable;

    QString newMessage = record + QString(tr("\n    ")) + QString(data);

    ui->m_teRecv->setText(newMessage);
    ui->m_teSend->setText("");
    ui->m_teSend->setFocus();
}
void Chat::processNewConnection()
{
    m_pClientConnection = m_ListenSocket.nextPendingConnection();
    setConnect();
    m_bIsConnected = true;
    m_Name = m_PeerIP = m_pClientConnection->peerAddress().toString();
    m_Port = m_PeerPort = m_pClientConnection->peerPort();

    ui->m_lbTitle->setText(QString("My friend [") +m_Name+ QString(tr("] connect to me")) );
}
void Chat::processConnected()
{
    ui->m_lbTitle->setText(QString("connect to [") + m_Name + QString("] for chat"));
    m_bIsConnected = true;
}
void Chat::processDisconnected()
{
    m_pClientConnection->close();
    ui->m_lbTitle->setText(QString("<font color=red>your friend [") + m_Name + QString("] has disconnected with you</font>"));
    m_bIsConnected = false;
}
void Chat::processReadyRead()
{
    //===========TEST================================
    MSGHeader header;

    QByteArray data;
    QByteArray h;

    h = m_pClientConnection->read(sizeof(header));
    memcpy(&header,h.data(),sizeof(header));

    data = m_pClientConnection->read(header.len);

    //===============================================
    processNewData(data);
}
void Chat::processNewData(QByteArray data)
{
    ///deal new chat data recive from client
    QString str = ui->m_teRecv->toPlainText();

    QTime time = QTime::currentTime();
    QString time_str = time.toString("hh:mm:ss");

    QString lable = m_PeerIP + QString(tr(" ")) + time_str;
    QString record ;
    if (!str.isEmpty())
        record= str + QString(tr("\n")) + lable;
    else
        record = lable;

    QString newMessage = record + QString(tr("\n    ")) + QString(data);

    ui->m_teRecv->setText(newMessage);

}
void Chat::processConnectionChange(QString name, QString ip, int port)
{
    m_Name = name;
    m_IP = ip;
    m_Port = port;
    m_bIsConnected = true;

    if (m_pClientConnection->isValid() || m_pClientConnection != 0)
    {
        m_pClientConnection->close();
        m_pClientConnection->connectToHost(QHostAddress(ip),port);
        setConnect();

        m_PeerIP = m_pClientConnection->peerAddress().toString();
        m_PeerPort = m_pClientConnection->peerPort();
    }
}
bool Chat::startListen(QString ip, int port)
{
    QHostAddress IP(ip);
    return m_ListenSocket.listen(IP,port);
}
void Chat::setConnect()
{
    connect(m_pClientConnection,SIGNAL(connected()),this,SLOT(processConnected()));
    connect(m_pClientConnection,SIGNAL(disconnected()),this,SLOT(processDisconnected()));
    connect(m_pClientConnection,SIGNAL(readyRead()),this,SLOT(processReadyRead()));
}
